<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class StorePlatform extends Model
{
    use HasDateTimeFormatter;
    use SoftDeletes;

    protected $table = 'ims_yz_store_platform';
    
    protected $fillable = [
        'uniacid',
        'platformcode',
        'platformname', 
        'applyname',
        'authorizationlimit',
        'yhexchangelt',
        'yhexchangert',
        'yhpromolt',
        'yhpromort',
        'status',
        'created_at',
        'updated_at',
        'deleted_at'
    ];

    protected $casts = [
        'uniacid' => 'integer',
        'status' => 'integer',
        'created_at' => 'integer',
        'updated_at' => 'integer',
        'deleted_at' => 'integer'
    ];

    // 使用时间戳格式
    public $timestamps = false;

    /**
     * 获取平台下的所有门店
     */
    public function stores()
    {
        return $this->hasMany(Store::class, 'platform_id');
    }

    /**
     * 获取平台下的供应商
     */
    public function vendors()
    {
        return $this->hasMany(Vendor::class, 'platform_id');
    }

    /**
     * 获取激活状态的平台列表
     */
    public static function getActivePlatforms()
    {
        return self::where('status', 1)
                   ->orderBy('id', 'asc')
                   ->get();
    }

    /**
     * 获取平台的供应商数量
     */
    public function getVendorCountAttribute()
    {
        return $this->vendors()->count();
    }

    /**
     * 获取平台的门店数量
     */
    public function getStoreCountAttribute()
    {
        return $this->stores()->count();
    }

    /**
     * 检查平台是否激活
     */
    public function isActive()
    {
        return $this->status === 1;
    }

    /**
     * 获取平台状态文本
     */
    public function getStatusTextAttribute()
    {
        return $this->status === 1 ? '正常' : '停用';
    }

    /**
     * 获取平台名称（兼容新旧字段）
     */
    public function getPlatformNameAttribute()
    {
        return $this->attributes['platformname'] ?? null;
    }

    /**
     * 获取平台编码（兼容新旧字段）
     */
    public function getPlatformCodeAttribute()
    {
        return $this->attributes['platformcode'] ?? null;
    }

    /**
     * 获取授权额度
     */
    public function getAuthorizationLimitAttribute()
    {
        return $this->authorizationlimit;
    }

    /**
     * 获取YH兑换比例
     */
    public function getYhExchangeRatioAttribute()
    {
        return [
            'left' => $this->yhexchangelt,
            'right' => $this->yhexchangert
        ];
    }

    /**
     * 获取YH促销比例
     */
    public function getYhPromoRatioAttribute()
    {
        return [
            'left' => $this->yhpromolt,
            'right' => $this->yhpromort
        ];
    }

    /**
     * 根据平台代码查找平台
     */
    public static function findByCode($code)
    {
        return self::where('platformcode', $code)->first();
    }

    /**
     * 获取平台的所有相关数据（带统计）
     */
    public static function getPlatformsWithStats()
    {
        $platforms = self::where('status', 1)
                         ->orderBy('id', 'asc')
                         ->get();
        
        $colors = ['primary', 'success', 'info', 'warning', 'secondary'];
        
        return $platforms->map(function ($platform) use ($colors) {
            $color = $colors[$platform->id % count($colors)];
            
            // 手动查询统计数据
            $vendorCount = Vendor::where('platform_id', $platform->id)
                                ->where('status', 1)
                                ->count();
            
            $storeCount = Store::where('platform_id', $platform->id)
                              ->count();
            
            return [
                'id' => $platform->id,
                'name' => $platform->platformname,
                'code' => $platform->platformcode,
                'apply_name' => $platform->applyname,
                'authorization_limit' => $platform->authorizationlimit,
                'store_count' => $storeCount,
                'vendor_count' => $vendorCount,
                'status' => $platform->status === 1 ? '正常' : '停用',
                'active' => $platform->status === 1,
                'color' => $color
            ];
        });
    }

    /**
     * 获取平台的颜色样式类
     */
    public function getColorClass()
    {
        $colors = ['primary', 'success', 'info', 'warning', 'secondary'];
        return $colors[$this->id % count($colors)];
    }
}